// 这个是开发测试文件
import IDB from '../lib/index'

let idb = new IDB('demo', 1, {

    onupgradeneeded(evt) {

        const db: IDBDatabase = (evt.target as IDBOpenDBRequest).result;

        if (!db.objectStoreNames.contains('book')) {
            let objectStore = db.createObjectStore('book', { keyPath: 'id', autoIncrement: true });
            objectStore.createIndex('id', 'id', { unique: true });
            objectStore.createIndex('name', 'name', { unique: true });
            objectStore.createIndex('type', 'type', { unique: false });
        }

    },

    onsuccess(evt) {
        listBook()
    },

});


let tbody = document.getElementById('list-body') as HTMLBodyElement;
let inputBookName = document.getElementById('input-bookname') as HTMLInputElement;
let inputBookType = document.getElementById('input-booktype') as HTMLSelectElement;

// 添加
document.getElementById('btn-addbook')!.addEventListener('click', evt => {
    idb
        .store('book')
        .add({
            name: inputBookName.value,
            type: inputBookType.value
        })
        .then(res => listBook())
        .catch(err => console.log('addError', err))
});

// 批量添加
document.getElementById('btn-adds')!.addEventListener('click', evt => {
    idb.store('book').adds([
        { name: '小老鼠抓小猫的故事', type: '故事书' },
        { name: '中国人要有信仰', type: '教科书' },
        { name: '谁是最可恨的人', type: '故事书' },
        { name: '为什么要天天向上', type: '教科书' },
        { name: '问我啥都不知道', type: '科学书' },
        { name: '跟我学画大鸭蛋', type: '美术书' },
        { name: '体育课上学数学', type: '教科书' },
    ]).then(res => {
        console.log('adds', res);
        listBook();
    });
});


// 删除、修改
document.body.addEventListener('click', evt => {

    let target = evt.target as HTMLElement;

    // 删除
    if (target.classList.contains('btn-remove')) {
        idb.store('book').delete(Number(target.dataset.key!)).then(res => listBook());
    }

    // 修改
    if (target.classList.contains('btn-update')) {

        let oldValue = JSON.parse(target.dataset.value!);

        idb.store('book').update({
            ...oldValue,
            name: prompt('请输入新书名')
        }).then(res => listBook());

    }

    // 过滤
    if (target.classList.contains('input-filter')) {
        listBook();
    }

});

// 清除库数据
document.getElementById('btn-clearstore')!.addEventListener('click', evt => {
    idb.store('book').clear().then(res => listBook());
});

// 列表
function listBook() {

    let radios = [...document.getElementsByClassName('input-filter')] as HTMLInputElement[];
    let filterType = (radios.find((el) => el.checked) as HTMLInputElement).value;
    let filter = filterType === 'all' ? undefined : data => data.type === filterType; // 过滤器

    idb.store('book').gets(filter).then(data => {

        tbody.innerHTML = '';
        data.forEach(item => {

            let node = document.createElement('tr');
            node.innerHTML = `
                <tr>
                    <td>${item.id}</td>
                    <td>${JSON.stringify(item)}</td>
                    <td>
                        <button class="btn-remove" data-key="${item.id}">删除</button>
                        <button class="btn-update" data-key="${item.id}" data-value='${JSON.stringify(item)}'>修改</button>
                    </td>
                </tr>
            `;

            tbody?.append(node);

        });
    });
}